package edu.xmut.yuepaibackend.service.impl;

import edu.xmut.yuepaibackend.model.domain.SysPicture;
import edu.xmut.yuepaibackend.service.AsyncUploadService;
import edu.xmut.yuepaibackend.service.SysPictureService;
import edu.xmut.yuepaibackend.utils.COSUploadPictureResult;
import edu.xmut.yuepaibackend.utils.COSUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


@Slf4j
@Service
public class AsyncUploadServiceImpl implements AsyncUploadService {

    @Resource
    private COSUtils cosUtils;

    @Resource
    private SysPictureService sysPictureService;

    @Override
    @Async("uploadThreadPoolExecutor")
    public void asyncUploadPictureAndSaveToDB(long id, MultipartFile multipartFile) {
        // 得到图片的原始文件名
        String originalFilename = multipartFile.getOriginalFilename();
        // 生成图片随机文件名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 得到图片对象key
        String key = id + suffix;
        // 上传
        COSUploadPictureResult result = cosUtils.uploadPicture(multipartFile, key);
        log.info("图片上传成功，{}", id);
        // 保存到数据库
        SysPicture sysPicture = new SysPicture();
        sysPicture.setId(id);
        sysPicture.setDefaultUrl(result.getDefaultUrl());
        sysPicture.setPreviewUrl(result.getPreviewUrl());
        sysPicture.setWidth(result.getWidth());
        sysPicture.setHeight(result.getHeight());
        sysPictureService.save(sysPicture);
        log.info("图片保存到数据库成功，{}", id);
    }
}
